const db = wx.cloud.database()
const _ = db.command

Page({
  data: {
    favorites: []
  },

  onLoad() {
    this.loadFavorites()
  },

  onShow() {
    // 每次显示页面时重新加载收藏列表
    this.loadFavorites()
  },

  loadFavorites() {
    wx.showLoading({
      title: '加载中...'
    })

    const userInfo = wx.getStorageSync('userInfo')

    if (!userInfo || !userInfo._id) {
      wx.hideLoading()
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 从myfavorites表查询用户的收藏记录
    db.collection('myfavorites')
      .where({
        userId: userInfo._id
      })
      .orderBy('collectionTime', 'desc')  // 按收藏时间倒序排列
      .get()
      .then(async res => {
        const favorites = res.data
        
        // 获取所有收藏的菜品ID
        const dishIds = favorites.filter(f => f.dishId).map(f => f.dishId)
        
        if (dishIds.length === 0) {
          this.setData({
            favorites: []
          })
          wx.hideLoading()
          return
        }

        // 查询收藏的菜品详细信息
        const dishes = await db.collection('mydishes')
          .where({
            _id: _.in(dishIds)
          })
          .get()

        // 将收藏时间等信息合并到菜品数据中
        const dishesWithFavoriteInfo = dishes.data.map(dish => {
          const favoriteInfo = favorites.find(f => f.dishId === dish._id)
          return {
            ...dish,
            collectionTime: favoriteInfo.collectionTime
          }
        })

        this.setData({
          favorites: dishesWithFavoriteInfo
        })
        wx.hideLoading()
      })
      .catch(err => {
        console.error('加载收藏失败：', err)
        wx.hideLoading()
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        })
      })
  },

  navigateToDish(e) {
    const { dishId } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/dish-detail/dish-detail?dishId=${dishId}`
    })
  },

  toggleFavorite(e) {
    const { dishId } = e.currentTarget.dataset
    
    // 防止事件冒泡
    e.stopPropagation()

    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo || !userInfo._id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 从myfavorites表中删除收藏记录
    db.collection('myfavorites')
      .where({
        userId: userInfo._id,
        dishId: dishId
      })
      .remove()
      .then(() => {
        // 从列表中移除该菜品
        const favorites = this.data.favorites.filter(dish => dish._id !== dishId)
        this.setData({ favorites })
        
        wx.showToast({
          title: '已取消收藏',
          icon: 'success'
        })
      })
      .catch(err => {
        console.error('取消收藏失败：', err)
        wx.showToast({
          title: '操作失败',
          icon: 'error'
        })
      })
  }
}) 